package bma.common.netty.webserver.ai;

import java.util.concurrent.atomic.AtomicInteger;

import bma.common.netty.webserver.Session;
import bma.common.netty.webserver.common.SessionManagerAbstract;

public class SessionManager4AI extends SessionManagerAbstract {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(SessionManager4AI.class);

	protected AtomicInteger totalSize = new AtomicInteger();

	protected class SessionCache4AI extends SessionCache {

		public SessionCache4AI(int initialCapacity) {
			super(initialCapacity, null);
		}

		@Override
		protected void addSize(int v) {
			totalSize.addAndGet(v);
			super.addSize(v);
		}

		@Override
		protected boolean isOverload() {
			if (totalSize.get() > maxSessionDataSize) {
				return true;
			}
			return super.isOverload();
		}
	}

	protected int maxSessionDataSize = 1024;

	// runtime
	protected ThreadLocal<SessionCache> localData = new ThreadLocal<SessionCache>();

	public int getMaxSessionDataSize() {
		return maxSessionDataSize;
	}

	public void setMaxSessionDataSize(int maxSessionDataSize) {
		this.maxSessionDataSize = maxSessionDataSize;
	}

	@Override
	public Session getSession(String sid, boolean created) {
		SessionCache sc = localData.get();
		if (sc == null) {
			sc = new SessionCache4AI(this.sessionDataSize);
			localData.set(sc);
		}
		return super.getSession(sc, sid, created);
	}
}
